package com.lonely.fx.list_view;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

import java.util.Comparator;
import java.util.function.Predicate;

/**
 * @date: 2022-07-29 15:11
 * @author: ztkj-hzb
 * @description: 筛选和排序 演示
 **/
public class FilterAndSortSettingMain extends Application {


    public static void main(String[] args) {
        launch(args);
    }

    /**
     *
     */
    @Override
    public void start(Stage primaryStage) throws Exception {

        AnchorPane anchorPane = new AnchorPane();

        HBox hBox = new HBox();
        hBox.setPrefHeight(100);
        hBox.setAlignment(Pos.CENTER);
        hBox.setSpacing(30);
        TextField textField = new TextField();
        Button ascBtn = new Button("升序");
        Button descBtn = new Button("降序");


        ObservableList<String> list = FXCollections.observableArrayList();
        list.add("A0");
        list.add("B0");
        list.add("C0");
        list.add("D0");
        list.add("E0");
        list.add("F0");
        list.add("A1");
        list.add("B1");
        list.add("C1");
        list.add("D1");
        list.add("E1");
        list.add("F1");

        ListView<String> listView = new ListView<>(list);
        listView.setPrefSize(300,300);
        listView.setFixedCellSize(30);


        hBox.getChildren().addAll(textField,ascBtn,descBtn);
        AnchorPane.setLeftAnchor(listView,100.0);
        AnchorPane.setTopAnchor(listView,100.0);
        anchorPane.getChildren().addAll(hBox,listView);
        primaryStage.setScene(new Scene(anchorPane));
        primaryStage.setWidth(500);
        primaryStage.setHeight(500);
        primaryStage.show();

        hBox.prefWidthProperty().bind(anchorPane.widthProperty());


        //搜索
        textField.textProperty().addListener((observable, oldValue, newValue) -> {
            FilteredList<String> filtered = list.filtered(s -> s.contains(newValue));
            listView.setItems(filtered);
        });

        //升序
        ascBtn.setOnAction(event -> {
            SortedList<String> sorted = listView.getItems().sorted(String::compareTo);
            listView.setItems(sorted);
        });

        //降序
        descBtn.setOnAction(event -> {
            SortedList<String> sorted = listView.getItems().sorted(Comparator.reverseOrder());
            listView.setItems(sorted);
        });


    }
}
